var Log = {
	elem: $('log'),
	write: function(text) {
		if(!this.elem) this.elem = $('log');
		this.elem.set('html', text);
	}
};

var myAwesomeCanves = null, myAwesomeGRaph = null;

function init(json, root) {
	//computes page layout (not a library function, used to adjust some css thingys on the page)
	Infovis.initLayout();
	 //Stores canvas current lineWidth property value
	 var lineW;
	 
	 //Set nodes interpolation to 'polar' (you can also use 'linear')
	 Config.interpolation = 'polar';
	 //Don't draw concentric background circles
         Config.allowConcentricCircles = false;
	 Config.drawConcentricCircles = false;
	 //Set the distance between concentric circles (or tree levels)
	 Config.levelDistance = 120;
	 //Set animation time
	 Config.animationTime = 1000;


	 //Allow weighted nodes. If setted to true, 
	 //it will take the first data set object value property (i.e node.data[0].value)
	 //to set the node diameter. 
	 Config.allowVariableNodeDiameters = true;
	//Set node diameters range. For variable node weights.
	Config.nodeRangeDiameters = {
		min: 10,
		max: 35
	};
	//The interval of the values of the first object of your dataSet array. A superset of the values can also be specified.
	Config.nodeRangeValues = {
		min: 1,
		max: 35
	};

	

    //Take width and height of the main container.
    var infovis = $('infovis');
    var w = infovis.offsetWidth, h = infovis.offsetHeight;
    //Create a new canvas instance.
    if (myAwesomeCanves == null) {
      myAwesomeCanves = new Canvas('mycanvas', {
          //Where to inject the canvas. Any div container will do.
          'injectInto':'infovis',
          //width and height for canvas. Default's to 200.
          'width': w,
          'height':h,
          //Canvas styles
          'styles': {
              'fillStyle': '#ccddee',
              'strokeStyle': '#772277'
          },
          //Add a background canvas for plotting
          //concentric circles.
          'backgroundCanvas': {
              //Add Canvas styles for the bck canvas.
              'styles': {
                  'fillStyle': '#444',
                  'strokeStyle': '#444'
              },
              //Add the initialization and plotting functions.
              'impl': {
                  'init': $empty,
                  'plot': function(canvas, ctx) {
                    /*
                      var times = 10, d = Config.levelDistance;
                      var pi2 = Math.PI*2;
                      for(var i=1; i<=times; i++) {
                          ctx.beginPath();
                          ctx.arc(0, 0, i * d, 0, pi2, true);
                          ctx.stroke();
                          ctx.closePath();
                      }
                      */
                  }
              }
          }   
      });
    } // end myAwesomeCanves
    
    var canvas = myAwesomeCanves;
    canvas.clear();
    if (myAwesomeGRaph == null) {
     var rgraph= new RGraph(canvas,  {
        //Use onBeforePlotLine and onAfterPlotLine controller
        //methods to adjust your canvas lineWidth
        //parameter in order to plot weighted edges on 
        //your graph. You can also change the color of the lines.
        onBeforePlotLine: function(adj) {
                        lineW = canvas.getCtx().lineWidth;
                        canvas.getCtx().lineWidth = adj.data.weight;
        },

        onAfterPlotLine: function(adj) {
                        canvas.getCtx().lineWidth = lineW;
        },

        onBeforeCompute: function(node) {
                //Log.write("centering " + node.name + "...");
                /*
                var html = "<h4>" + node.name + "</h4><b>Connections:</b>";
                html += "<ul>";
                GraphUtil.eachAdjacency(node, function(adj) {
                        var child = adj.nodeTo;
                        html += "<li>" + child.name+ "</li>";
                });
                html+= "</ul>";
                $('inner-details').set("html", html);
                */
        },
	  	
    //Assign html to each label and some effects.	
	onCreateLabel: function(domElement, node) {
          var elem = $(domElement);
          elem.setStyle('color', '#aaa').set('html', node.name).addEvents({
            'mouseenter': function() {
              elem.setStyle('color', '#fff')
              elem.setStyle('z-index', 1000)
            },

            'mouseleave': function() {
              elem.setStyle('color', '#aaa')
              elem.setStyle('z-index', 100)
            },

            'click': function() {
                            rgraph.onClick(node.id);
            }
          });
	},
	
	//Take off previous width and height styles and
	//add half of the *actual* label width to the left position
	// That will center your label (do the math man). 
	onPlaceLabel: function(domElement, node) {
		domElement.innerHTML = '';
		domElement.innerHTML = node.name;
		var left = parseInt(domElement.style.left);
		domElement.style.width = '';
		domElement.style.height = '';
		var w = domElement.offsetWidth;
		domElement.style.left = (left - w /2) + 'px';
	},
	
	onAfterCompute: function() {
		//Log.write("done");
	}
	  	
	});
        myAwesomeGRaph = rgraph;
    }
    
    
	  //load weighted graph.
        myAwesomeGRaph.loadGraphFromJSON(json, 1);

	//compute positions and plot = refresh.
	myAwesomeGRaph.refresh();
	myAwesomeGRaph.controller.onBeforeCompute(GraphUtil.getNode(myAwesomeGRaph.graph, myAwesomeGRaph.root));
	myAwesomeGRaph.controller.onAfterCompute();
        if (root != null) {
          myAwesomeGRaph.onClick(root);
        }
}
